import { useEffect, useState } from "react";
import { Button, Input, Modal, message } from "antd";
import { qrListGet, addQrGroup } from "@/assets/js/networkRequest/method";
import { SelectGroup } from "@/components/func";
// 分组
import ContentLeft from "./content-left/qr_content_left";
// 表格
import ContentRight from "./content-right/qr_content_right";

// 总数据
let total = 0;
// 默认分组数据
let defaultGroup: any = {};
// 表格数据
let totalFormData: any = [];
// 初始表格数据
let initFormData: any = [];
// 添加下一个分组需要的顺序号
let order = 0;

const QrList = () => {
  const [, setRender] = useState(0);
  const [loding, setLoding] = useState(true);
  const [visible, setVisible] = useState(false);
  const [qrGroupId, setQrGroupId] = useState(0);
  const [selectedQr, setSelectedQr] = useState([]);
  let [listGroupData, setListGroupData]: any = useState([]);

  /* 每次对列表数据处理之后进行一次初始化操作 */
  const initQrGroupData = (newListData: any) => {
    newListData.sort((a: any, b: any) => {
      return a.order - b.order;
    });
    // 保存下一个添加分组时需要的排序号
    order = newListData.length ? newListData[newListData.length - 1].order + 1 : 1;
    setListGroupData(newListData);
    setRender(Math.random() + 1);
  };

  /* 添加分组 */
  const addGroup = async (name: string) => {
    await addQrGroup({ name, order }).then((res: any) => {
      if (res.code === 200) {
        listGroupData.push({ ...res.data, count: 0 });
        initQrGroupData(listGroupData);
      }
    });
  };

  /* 初始化活码列表和活码分组数据 */
  const initData = async () => {
    setLoding(true);
    listGroupData = [];
    let res: any = await qrListGet({});
    // 处理活码表格数据
    initFormData = res.data.qrs.map((item: any, index: number) => {
      item.key = index;
      return item;
    });
    totalFormData = JSON.parse(JSON.stringify(initFormData));
    // 处理活码分组数据
    res.data.qr_group.map((item: any) => {
      if (item.name === "默认分类") {
        defaultGroup = item;
      } else {
        listGroupData.push(item);
      }
    });
    initQrGroupData(listGroupData);
    setLoding(false);
  };

  /* 搜索名称请求数据 */
  const searchName = async (e: string) => {
    /* 没有关键字时初始化 */
    if (!e) {
      initData();
      return;
    }
    /* 根据关键字更新活码列表 */
    let res: any = await qrListGet({ name: e });
    if (res.code === 200) {
      initFormData = res.data.map((item: any, index: number) => {
        item.key = index;
        return item;
      });
    } else {
      initFormData = [];
    }
    setRender(Math.random() + 1);
  };

  useEffect(() => {
    initData();

    /* 分组选择筛选数据 */
    window.globalState.getState("listData", async (value: number) => {
      setLoding(true);
      initFormData = value
        ? totalFormData.filter((item: any) => item.qr_group === value)
        : JSON.parse(JSON.stringify(totalFormData));
      setLoding(false);
      setRender(Math.random() + 1);
    });
    return () => {
      window.globalState.destoryState("listData");
    };
  }, []);

  return (
    <div className="qr-list h-full py-0 px-16 pb-10">
      {/* 对活码列表的操作 */}
      <div className="opera w-full flex items-center flex-row justify-between">
        <div>
          <Button
            className="mr-16"
            type="primary"
            onClick={() => {
              window.globalState.muState("history", {
                type: "push",
                pathname: "/qr/create",
                query: { a: 1 },
              });
            }}>
            新建活码
          </Button>
          <Button
            type="primary"
            ghost
            onClick={() => {
              if (!selectedQr.length) {
                message.warn("请选择需要分组的渠道码");
                return;
              }
              setVisible(true);
            }}>
            批量分组
          </Button>
          <a
            href="https://weibanzhushou.com/help_center?bar=liveCode"
            target="_blank"
            className="hover:text-blue-default text-sm text-grey-800 ml-10">
            什么是渠道活码？
          </a>
        </div>
        <div>
          <Input.Search
            allowClear
            style={{ width: "100%" }}
            defaultValue=""
            placeholder="请输入活码名称"
            onSearch={searchName}
          />
        </div>
      </div>

      {/* 渠道列表的分组列表和表格 */}
      <div className="qr-content flex mt-16">
        <ContentLeft
          total={total}
          listGroupData={listGroupData}
          defaultGroup={defaultGroup}
          initQrGroupData={initQrGroupData}
          addGroup={addGroup}
        />
        <ContentRight
          initFormData={initFormData}
          setSelectedQr={setSelectedQr}
          loding={loding}
        />
      </div>

      {/* 批量分组弹窗 */}
      <Modal
        closable={false}
        maskClosable={false}
        visible={visible}
        width={634}
        footer={null}
        onCancel={() => {
          setVisible(false);
        }}>
        <h2 className="dialog-title">选择标签</h2>

        <div className="flex items-center relative justify-center">
          <span className="w-106 text-right mr-16"> 选择分组:</span>
          <SelectGroup
            domId="area1"
            qrGroupId={qrGroupId}
            setQrGroupId={setQrGroupId}
            listGroupData={listGroupData}
            onPressEnter={(e: string) => {
              addGroup(e);
            }}
          />
        </div>

        <div className="btn-wrap">
          <div className="left"></div>
          <div className="right">
            <Button
              onClick={() => {
                setVisible(false);
              }}>
              取消
            </Button>
            <Button
              type="primary"
              onClick={() => {
                setVisible(false);
              }}>
              保存
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default QrList;
